<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <select class="province">
        <option value="">请选择省份</option>
        <!-- <option value="A001">北京</option>
        <option value="A002">上海</option>
        <option value="A003">湖北</option>
        <option value="A004">湖南</option> -->
    </select>
    <select class="city" name="" id="">
        <option value="">请选择市/区</option>
        <!-- <option value="A001">朝阳</option>
        <option value="A002">海淀</option>
        <option value="A003">沙河</option>
        <option value="A004">上地</option> -->
    </select>

</body>
<script>
    var province = document.querySelector(".province");
    var city = document.querySelector(".city");

    var xhr = new XMLHttpRequest();
    xhr.open("get", "../data/pro.json", true);
    xhr.send();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {

            var obj = JSON.parse(xhr.responseText); //获取JSON对象
            // console.log(obj);
            var { list: proList } = obj; //第一次解构，解构对象
            // console.log(proList);
            var html = `<option value="">请选择省份</option>`;
            citySwitch(proList, province, html);

            province.onchange = function () {
                var proId = province.value
                if (proId) {  //如果有值再进行

                    var thisPro = proList.find(({ city_id }) => { //找到第一个满足条件的元素，
                        return proId === city_id;
                    });

                    var { list: cityList } = thisPro;
                    var html = `<option value="">请选择市/区</option>`;
                    citySwitch(cityList, city, html);

                } else {
                    city.innerHTML = `<option value="">请选择市/区</option>`;
                }

            }

        }
    }

    //遍历数组解构里面的id和name,然后写到页面
    // arr:传入的数组  city: 下拉框的名字  html:html默认结构
    function citySwitch(arr, city, html) {
        arr.forEach(({ city_id, city_name }) => {
            html += `<option value="${city_id}">${city_name}</option>`;
        });
        city.innerHTML = html;
    }

</script>

</html>